import face_recognition
from flask import jsonify
from pkg import GenID
import random
import requests
import json
def CallOtherStorefaceDetAndEncodingToSQLAndMilvus(ImageArr, imageUrl, photoWeb, table, collection_name, storerapi):
      # img_encodings = face_recognition.face_encodings(ImageArr, model="cnn")
      # img_locations = face_recognition.face_locations(ImageArr, model="cnn")
      img_encodings = face_recognition.face_encodings(ImageArr)
      img_locations = face_recognition.face_locations(ImageArr)
      imgs = {}
      ids = {}
      if len(img_encodings) != len(img_locations):
          return jsonify({"state": "fail","info":"not find face"})
      #NewMilvusCLient(table)
      for i in range(len(img_locations)):
            img_encoding = img_encodings[i]
            img_location = str(img_locations[i])[1:-1]
            # store2milvus ▒~X▒~E▒▒~U▒▒~M▒▒~S
            # imgInfoID = storeImageImfo(imagePath, imageUrl, img_location)
            print("start call ", storerapi," to store encoding and location")
            # id, bl = Store2mysql(table, str(imgInfoID), imageUrl, img_location, photoWeb)
            # if bl == False :
            #       return jsonify({"state": "error mysql▒~O~R▒~E▒▒~J▒▒~T~Y", "ids": None})
            # Store2Milvus(id, img_encoding, collection_name)
            # ids[i] = (id, imgInfoID)
            id, imgInfoID = postToStoreOhther(imageUrl, photoWeb, img_location, img_encoding, table, collection_name, storerapi)
            ids[i] = (id, imgInfoID)

      return jsonify({"state": "OK", "ids": ids})

def postToStoreOhther(imageUrl, photoWeb, location, encoding, table, collection_name, storerapi):
    headers = {
        'Content-Type':'application/json; charset=UTF-8',
    }
    encodingstring = ','.join(str(i) for i in encoding)
    data = {"url": imageUrl,
            "photoWeb": photoWeb,
            "location": location,
            "encoding": encodingstring, # str = ','.join(str(i) for i in arr)
            "table": table,
            "collection_name": collection_name,
            }
    #resp = requests.post(url=url,data=json.dumps(data))
    resp = requests.post(url=storerapi,data=data)
    val = json.loads(resp.text)
    return val["ids"][0], val["ids"][1]

